<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Environment;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Yiisoft\Csrf\CsrfTokenMiddleware;

use function str_starts_with;

final class ApiCsrfBypassMiddleware implements MiddlewareInterface
{
    public function __construct(
        private CsrfTokenMiddleware $csrfTokenMiddleware,
    ) {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (Environment::isTest()) {
            return $handler->handle($request);
        }

        $path = $request->getUri()->getPath();

        if (str_starts_with($path, '/api/')) {
            return $handler->handle($request);
        }

        return $this->csrfTokenMiddleware->process($request, $handler);
    }
}
